#include "CDialog.h"

#include <QCloseEvent>
#include <QDebug>

CDialog::CDialog(QWidget *parent) : CTopWidget(parent) {
    init();
};

CDialog::~CDialog() {
}

void CDialog::init() {
    setWindowFlags((windowFlags() | Qt::Dialog) & ~Qt::WindowMinMaxButtonsHint);

    m_titleBar = new CDialogBar();
    m_titleBar->setObjectName("dialog-bar");

    m_layout->insertWidget(0, m_titleBar);

    connect(m_titleBar, &CDialogBar::closeRequested, this, &CDialog::handleClose);

    setResizable(false);
}

int CDialog::exec(Qt::WindowModality modal) {
    m_code = -1;

    setWindowModality(modal); // Block main thread

    show();

    prepareExec();
    m_loop.exec();

    return m_code;
}

void CDialog::prepareExec() {
}

bool CDialog::acceptClose() {
    return true;
}

void CDialog::handleClose() {
    close();
}

bool CDialog::isMouseOnCaption() const {
    return m_titleBar->isMouseFree();
}

bool CDialog::isNative() const {
    return m_titleBar->barVisible();
}

void CDialog::setNative(bool value) {
    m_titleBar->setVisible(value);
}

bool CDialog::titleVisible() const {
    return m_titleBar->isVisible();
}

void CDialog::setTitleVisible(bool titleVisible) {
    m_titleBar->setTitleVisible(titleVisible);
}

void CDialog::windowTitleChangeEvent(QEvent *event) {
    Q_UNUSED(event)
    QString title = windowTitle();
    m_titleBar->setWindowTitle(title);
}

void CDialog::closeEvent(QCloseEvent *event) {
    if (acceptClose()) {
        m_loop.exit();
        event->accept();
    } else {
        event->ignore();
    }
}

bool CDialog::nativeEvent(const QByteArray &eventType, void *message, long *result) {
    return CTopWidget::nativeEvent(eventType, message, result);
}
